const controlCardsConfig = window.CONFIG.CONTROL_CARDS

let controlCardData = {};

// 控制卡片初始化函数
function controlCardsInit() {
     const cardsContainer = document.getElementById('vehicle-controls');
     controlCardsConfig.forEach((item, index) => {
        let cardElement;

        // 检查是否有重复字段
        if (controlCardData[item.field]) {
            console.error(`字段 ${item.field} 在配置中重复定义`);
            alert(`字段 ${item.field} 在配置中重复定义`);
            return;
        }
        
        switch(item.type) {
            case 'number':
                cardElement = createNumberCard(item, index);
                break;
            case 'enum':
                cardElement = createEnumCard(item, index);
                break;
            case 'multi':
                cardElement = createMultiInputCard(item, index);
                break;
            default:
                console.error(`未知类型 ${item.type} 的控制卡片`);
                return;
        }

        
        cardsContainer.appendChild(cardElement);
        
        // 初始化卡片数据
        if (item.type === 'multi') {
            const multiData = {};
            item.fields.forEach(field => {
                multiData[field.field] = field.value;
            });
            controlCardData[item.field] = {
                'value':multiData,
                'enabled':item.enabled,
            };

        } else {
            controlCardData[item.field] = {
                'value':item.value,
                'enabled':item.enabled,
            };

        }
    });

}

// 创建数字输入卡片
function createNumberCard(config, index) {
    const card = document.createElement('div');
    card.className = 'control-card';
    card.innerHTML = `
        <div class="card-header">
            <h3>${config.title}</h3>
        </div>
        <div class="value-display-large" id="${config.field}-value">${config.value}</div>
        <div id="${config.field}-controls1" class="${config.enabled ? 'control-enabled' : 'control-disabled'}">
            <input type="range" id="${config.field}-slider" min="${config.min}" max="${config.max}" step="${config.step}" 
                    value="${config.value}" class="control-slider">
        </div>
        <div id="${config.field}-controls2" class="${config.enabled ? 'control-enabled' : 'control-disabled'}">
            <div class="number-input-group">
                <label class="number-input-label">值:</label>
                <input type="text" id="${config.field}-input" value="${config.value}" class="number-input">
            </div>
        </div>
        <button class="btn-min" id="${config.field}-apply">应用下方配置</button>
        <div id="${config.field}-controls3" class="${config.enabled ? 'control-disabled' : 'control-enabled'}">
            <label class="number-input-label">范围:</label>
            <div class="number-input-group">
                <input type="text" id="${config.field}-min" class="number-input" value="${config.min}" placeholder="最小值">
                <span>~</span>
                <input type="text" id="${config.field}-max" class="number-input" value="${config.max}" placeholder="最大值">
            </div>
            <label class="number-input-label">步长|初始:</label>
            <div class="number-input-group">
                <input type="text" id="${config.field}-step" class="number-input" value="${config.step}" placeholder="步长">
                <span>|</span>
                <input type="text" id="${config.field}-init" class="number-input" value="${config.init}" placeholder="初始值">
            </div>
        </div>
        <button class="enable-button ${config.enabled ? 'enabled' : 'disabled'}" id="${config.field}-enable">
            ${config.enabled ? '已启用' : '已禁用'}
        </button>
        <div class="help-text">${config.description}</div>
            
    `;
    
    // 添加事件监听
    const valueDisplay = card.querySelector(`#${config.field}-value`);
    const slider = card.querySelector(`#${config.field}-slider`);
    const valueInput = card.querySelector(`#${config.field}-input`);
    const applyBtn = card.querySelector(`#${config.field}-apply`);
    const valueMin = card.querySelector(`#${config.field}-min`);
    const valueMax = card.querySelector(`#${config.field}-max`);
    const valueStep = card.querySelector(`#${config.field}-step`);
    const valueInit = card.querySelector(`#${config.field}-init`);
    const enableBtn = card.querySelector(`#${config.field}-enable`);
    // 用于禁用的div
    const controlsDiv1 = card.querySelector(`#${config.field}-controls1`);
    const controlsDiv2 = card.querySelector(`#${config.field}-controls2`);
    const controlsDiv3 = card.querySelector(`#${config.field}-controls3`);


    // 滑杆监听逻辑
    slider.addEventListener('input', function() {
        valueInput.value = this.value; 
        valueDisplay.textContent = this.value;
        if (config.enabled) {
            controlCardData[config.field].value = parseFloat(this.value);
            updateOutput();
        }
    });
    // 数值输入框监听逻辑
    valueInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            // 禁用时不响应
            if (!config.enabled) return;
            let value = parseFloat(this.value) || config.value;
            
            value = Math.max(config.min, Math.min(config.max, value));
            this.value = value;
            slider.value = value;
            valueDisplay.textContent = value;
            if (config.enabled) {
                controlCardData[config.field].value = value;
                updateOutput();
            }
        }
    });

    // 应用下方配置按钮监听逻辑
    applyBtn.addEventListener('click', function() {
        // 启用时不响应
        if (config.enabled) {
            alert('请先禁用后应用');
            return;
        }
        let min = parseFloat(valueMin.value) || config.min;
        let max = parseFloat(valueMax.value) || config.max;
        let step = parseFloat(valueStep.value) || config.step;
        let init = parseFloat(valueInit.value) || config.init;
        valueMin.value = min;
        valueMax.value = max;
        valueStep.value = step;
        valueInit.value = init;

        // 检查输入值是否有效
        if (min >= max || step <= 0 || init < min || init > max) {
            alert('请输入有效范围、步长和初始值');
            return;
        }
        init = Math.max(min, Math.min(max, init));
        slider.min = min;
        slider.max = max;
        slider.step = step;
        config.min = min;
        config.max = max;
        config.step = step;
        config.init = init;
        updateOutput();
        
        const originalText = applyBtn.textContent;
        applyBtn.textContent = '已应用';
        setTimeout(() => {
            applyBtn.textContent = originalText;
        }, 2000);
    });

    // 启动禁用按钮监听逻辑
    enableBtn.addEventListener('click', function() {
        config.enabled = !config.enabled;
        controlsDiv1.className = `${config.enabled ? 'control-enabled' : 'control-disabled'}`
        controlsDiv2.className = `${config.enabled ? 'control-endabled' : 'control-disabled'}`
        controlsDiv3.className = `${config.enabled ? 'control-disabled' : 'control-enabled'}`
        valueInput.className = `number-input-group control-${config.enabled? 'enabled' : 'disabled'}`
        this.textContent = config.enabled ? '已启用' : '已禁用';
        this.className = `enable-button ${config.enabled ? 'enabled' : 'disabled'}`;
        controlCardData[config.field].enabled = config.enabled;
        // 若禁用，则回复初值
        if (!config.enabled) {
            slider.value = config.init;
            valueInput.value = config.init;
            valueDisplay.textContent = config.init;
            controlCardData[config.field].value = config.init;
        }
        updateOutput();
    });

    // 设置外部调用函数
    card.setEnable = function(enabled) {
        config.enabled = enabled;
        controlsDiv1.className = `${config.enabled ? 'control-enabled' : 'control-disabled'}`
        controlsDiv2.className = `${config.enabled ? 'control-endabled' : 'control-disabled'}`
        controlsDiv3.className = `${config.enabled ? 'control-disabled' : 'control-enabled'}`
        valueInput.className = `number-input-group control-${config.enabled? 'enabled' : 'disabled'}`
        enableBtn.textContent = config.enabled ? '已启用' : '已禁用';
        enableBtn.className = `enable-button ${config.enabled ? 'enabled' : 'disabled'}`;
        controlCardData[config.field].enabled = config.enabled;
        // 若禁用，则回复初值
        if (!config.enabled) {
            slider.value = config.init;
            valueInput.value = config.init;
            valueDisplay.textContent = config.init;
            controlCardData[config.field].value = config.init;
        }
        updateOutput();
    }

    return card;
}
// 创建枚举卡片
function createEnumCard(config, index) {
    const card = document.createElement('div');
    card.className = 'control-card';
    let buttonsHTML = '';
    config.options.forEach(option => {
        const isActive = option === config.value ? 'active' : '';
        buttonsHTML += `<button class="enum-button ${isActive}" id="${config.field}-${option}">${option}</button>`;
    });

    card.innerHTML = `
        <div class="card-header">
            <h3>${config.title}</h3>
        </div>
        <div class="value-display-large" id="${config.field}-value">NONE</div>  
        <div id="${config.field}-controls" class="${config.enabled ? 'control-enabled' : 'control-disabled'}">
            <div class="enum-select">
                ${buttonsHTML}
            </div>
        </div>
        <button class="enable-button ${config.enabled ? 'enabled' : 'disabled'}" id="${config.field}-enable">
            ${config.enabled ? '已启用' : '已禁用'}
        </button>
        <div class="help-text">${config.description}</div>
    `;

    // 添加事件监听
    const controlsDiv = card.querySelector(`#${config.field}-controls`);

    const valueDisplay = card.querySelector(`#${config.field}-value`);
    const buttons = controlsDiv.querySelectorAll('.enum-button');
    const enableBtn = card.querySelector(`#${config.field}-enable`);

    // 枚举按钮点击监听逻辑
    controlsDiv.addEventListener('click', function(e) {
        if (e.target.classList.contains('enum-button')) {
            buttons.forEach(button => button.classList.remove('active'));
            e.target.classList.add('active');
            valueDisplay.textContent = e.target.textContent;
            controlCardData[config.field].value = e.target.textContent;
            updateOutput();
        }
    });

    // 启动禁用按钮监听逻辑
    enableBtn.addEventListener('click', function() {
        config.enabled = !config.enabled;
        controlsDiv.className = `${config.enabled ? 'control-enabled' : 'control-disabled'}`
        this.textContent = config.enabled ? '已启用' : '已禁用';
        this.className = `enable-button ${config.enabled ? 'enabled' : 'disabled'}`;
        controlCardData[config.field].enabled = config.enabled;
        // 若禁用，则回复初值
        if (!config.enabled) {
            valueDisplay.textContent = config.init;
            controlCardData[config.field].value = config.init;
            buttons.forEach(button => {
                if (button.textContent === config.init) {
                    button.className = 'enum-button active';
                } else {
                    button.className = 'enum-button';
                }
            });
            // 同步修改配置
            config.options.forEach(field => {
                if (field.field === config.field) {
                    field.value = field.init;
                }
            });

        }
        updateOutput();
    });

    // 设置外部调用函数
    card.setEnable = function(enabled) {
        config.enabled = enabled;
        controlsDiv.className = `${config.enabled ? 'control-enabled' : 'control-disabled'}`
        enableBtn.textContent = config.enabled ? '已启用' : '已禁用';
        enableBtn.className = `enable-button ${config.enabled ? 'enabled' : 'disabled'}`;
        controlCardData[config.field].enabled = config.enabled;
        // 若禁用，则回复初值
        if (!config.enabled) {
            valueDisplay.textContent = config.init;
            controlCardData[config.field].value = config.init;
            buttons.forEach(button => {
                if (button.textContent === config.init) {
                    button.className = 'enum-button active';
                } else {
                    button.className = 'enum-button';
                }
            });
        }
        updateOutput();
    }
    
    return card;
}

// 创建多输入卡片
function createMultiInputCard(config, index) {
    const card = document.createElement('div');
    card.className = 'control-card';
    let inputsHTML = '';
    config.fields.forEach(field => {
        inputsHTML += `
            <div class="multi-input-group">
                <div class="multi-input-label-group">
                    <label class="multi-input-label">${field.label}</label>
                    <label class="multi-input-datatype">${field.dataType}</label>
                </div>
                <div class="value-display-small" id="${config.field}-${field.field}-value">${field.value}</div>
                <input type="${field.dataType}" id="${config.field}-${field.field}" class="multi-input" value="${field.value}">
            </div>
        `;
    });
    card.innerHTML = `
        <div class="card-header">
            <h3>${config.title}</h3>
        </div>
        <div id="${config.field}-controls" class="${config.enabled ? 'control-enabled' : 'control-disabled'}">
            ${inputsHTML}
        </div>
        <button class="enable-button ${config.enabled ? 'enabled' : 'disabled'}" id="${config.field}-enable">
            ${config.enabled ? '已启用' : '已禁用'}
        </button>
        <div class="help-text">${config.description}</div>
    `;

    // 添加事件监听
    const controlsDiv = card.querySelector(`#${config.field}-controls`);
    const enableBtn = card.querySelector(`#${config.field}-enable`);
    const inputs = controlsDiv.querySelectorAll('.multi-input');


    // 输入框值改变监听逻辑
    inputs.forEach(input => {
        input.addEventListener('keypress', function(e) {
            // 回车触发 
            if (e.key === 'Enter') {
                if (input.type === 'number') {
                    controlCardData[config.field].value[input.id.split('-')[1]] = parseFloat(this.value);
                    const valueDisplay = controlsDiv.querySelector(`#${config.field}-${input.id.split('-')[1]}-value`);
                    valueDisplay.textContent = this.value;
                    input.value = parseFloat(this.value);
                    // 同步修改配置
                    config.fields.forEach(field => {
                        if (field.field === input.id.split('-')[1]) {
                            field.value = parseFloat(this.value);
                        }
                    });
                } else {
                    controlCardData[config.field].value[input.id.split('-')[1]] = this.value;
                    const valueDisplay = controlsDiv.querySelector(`#${config.field}-${input.id.split('-')[1]}-value`);
                    valueDisplay.textContent = this.value;
                    // 同步修改配置
                    config.fields.forEach(field => {
                        if (field.field === input.id.split('-')[1]) {
                            field.value = this.value;
                        }
                    });
                }
                

                updateOutput();
            }
        });
    });



    // 启动禁用按钮监听逻辑
    enableBtn.addEventListener('click', function() {
        config.enabled = !config.enabled;
        controlsDiv.className = `${config.enabled ? 'control-enabled' : 'control-disabled'}`
        this.textContent = config.enabled ? '已启用' : '已禁用';
        this.className = `enable-button ${config.enabled ? 'enabled' : 'disabled'}`;
        controlCardData[config.field].enabled = config.enabled;
        // 若禁用，则回复初值
        if (!config.enabled) {
            config.fields.forEach(field => {
                const input = controlsDiv.querySelector(`#${config.field}-${field.field}`);
                input.value = field.init;
                controlCardData[config.field].value[field.field] = field.init;
                // 同步修改配置
                field.value = field.init;
            });
        }
        updateOutput();
    });

    // 设置外部调用函数
    card.setEnable = function(enabled) {
        config.enabled = enabled;
        controlsDiv.className = `${config.enabled ? 'control-enabled' : 'control-disabled'}`
        enableBtn.textContent = config.enabled ? '已启用' : '已禁用';
        enableBtn.className = `enable-button ${config.enabled ? 'enabled' : 'disabled'}`;
        controlCardData[config.field].enabled = config.enabled;
        // 若禁用，则回复初值
        if (!config.enabled) {
            config.fields.forEach(field => {
                const input = controlsDiv.querySelector(`#${config.field}-${field.field}`);
                input.value = field.init;
                controlCardData[config.field].value[field.field] = field.init;
            });
        }
        updateOutput();
    }

    return card;
}

// 更新全部控制卡片的输出值
function updateOutput(){
    const output = {};
    for (const key in controlCardData) {
        const data = controlCardData[key];
        if (data.enabled) {
            output[key] = data.value;
        }
    }
    // console.log('Card output'+JSON.stringify(output));
    return output;
}

// 注册全局函数，获取所有卡片的控制值
window.getControlCardValues = function() {
    return updateOutput();
}


// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', controlCardsInit);